package com.educate.book.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.util.StringUtils;

import com.educate.book.model.bo.ChildBookBO;
import com.educate.book.model.po.ChildBook;
import com.educate.common.mongo.QueryUtils;

public class ChildBookDaoImpl {

	@Resource
	MongoTemplate mongoTemplate;

	public Page<ChildBook> query(ChildBookBO bo, Pageable pageable) {
		List<Criteria> andCriteria = new ArrayList<>(10);
//        Criteria keyCriteria = QueryUtils.keyWord(keyWord, "qq", "wx", "tb");
//        if (keyCriteria != null) {
//            andCriteria.add(keyCriteria);
//        }
//        if (startTime != null || endTime != null) {
//            Criteria createTime = Criteria.where("createTime");
//            if (startTime != null) {
//                createTime.gt(startTime);
//            }
//            if (endTime != null) {
//                createTime.lt(endTime);
//            }
//            andCriteria.add(createTime);
//        }
		if (!StringUtils.isEmpty(bo.getBookId())) {
			andCriteria.add(Criteria.where("bookId").is(bo.getBookId()));
		}
		if (!StringUtils.isEmpty(bo.getChildId())) {
			andCriteria.add(Criteria.where("childId").is(bo.getChildId()));
		}
		if (!StringUtils.isEmpty(bo.getBookId())) {
			andCriteria.add(Criteria.where("userId").is(bo.getUserId()));
		}
		if(StringUtils.isEmpty(bo.getState())) {
			andCriteria.add(Criteria.where("state").is(bo.getState()));
		}
		Query query = QueryUtils.query(andCriteria).with(pageable);
		query.with(new Sort(new Order(Direction.DESC, "progress"), new Order(Direction.DESC, "crateTime")));
		List<ChildBook> list = mongoTemplate.find(query, ChildBook.class);
		return PageableExecutionUtils.getPage(list, pageable, () -> mongoTemplate.count(query, ChildBook.class));

	}

	public List<ChildBook> queryByUserIdChildIdBookId(ChildBookBO bo) {
		List<Criteria> andCriteria = new ArrayList<>(10);
		if (!StringUtils.isEmpty(bo.getBookId())) {
			andCriteria.add(Criteria.where("bookId").is(bo.getBookId()));
		}
		if (!StringUtils.isEmpty(bo.getChildId())) {
			andCriteria.add(Criteria.where("childId").is(bo.getChildId()));
		}
		if (!StringUtils.isEmpty(bo.getBookId())) {
			andCriteria.add(Criteria.where("userId").is(bo.getUserId()));
		}
		Query query = QueryUtils.query(andCriteria);
		List<ChildBook> list = mongoTemplate.find(query, ChildBook.class);
		return list;

	}

}
